package com.morty.user.service.impl;

import com.morty.user.entity.User;
import com.morty.user.entity.UserLock;
import com.morty.user.mapper.management.UserLockMapper;
import com.morty.user.mapper.management.UserMapper;
import com.morty.user.service.UserService;
import io.seata.spring.annotation.GlobalLock;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.transaction.Propagation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

	@Resource
	UserMapper userMapper;

	@Resource
	UserLockMapper userLockMapper;


	public User getUserById(String userId){
		User user = userMapper.selectByPrimaryKey(userId);
		return user;
	}

	@GlobalLock(lockRetryTimes=1000)
	public UserLock getUserLockById(String userId){
		UserLock user = userLockMapper.selectByPrimaryKey(userId);
		return user;
	}

	/**
	 * 新增
	 * @param user
	 * @return
	 */
	@GlobalTransactional(propagation=Propagation.REQUIRES_NEW,name="insertUser")
	public int insertUser(User user){
		LOGGER.info("------->insertUser start-------<");
		//模拟超时异常，全局事务回滚
//		try {
//			Thread.sleep(30*1000);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
		return userMapper.insert(user);
	}

	/**
	 * 修改/作废
	 * @param user
	 * @return
	 */
	public int updateUser(User user){
		return userMapper.updateById(user);
	}

	public int updateUserLock(UserLock user){
		return userLockMapper.updateById(user);
	}
}
